//
//  UpdatePassViewController.m
//  OrderSeat
//
//  Created by 王威 on 14-2-17.
//  Copyright (c) 2014年 wangwei. All rights reserved.
//

#import "UpdatePassViewController.h"
#import "LoginViewController.h"

@implementation UpdatePassViewController

- (id)init
{
    self = [super initWithNibClass:[UpdatePassViewController class]];
    if (self) {
        _dataSource = [[UpdatePassDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"修改密码"];
    [_theView drawBorder];
}

- (IBAction)submitAction:(id)sender
{
    if (![self checkForm]) return;
    
    NSString *oldPass = _oldPassTF.text;
    NSString *nPass = _passTF.text;
    
    NSString *url = [NSString stringWithFormat:API_UPDATE_PASS, [AppSetting userName],oldPass,nPass];
    [_dataSource updateWithURL:url];
}

- (BOOL)checkForm
{
    if ([_oldPassTF.text isEqualToString:S_EMPTY]) {
        [AppDelegate showMessage:@"旧密码不能为空！"];
        return NO;
    }
    
    if ([_passTF.text isEqualToString:S_EMPTY]) {
        [AppDelegate showMessage:@"新密码不能为空！"];
        return NO;
    }
    
    if ([_comfirmPassTF.text isEqualToString:S_EMPTY]) {
        [AppDelegate showMessage:@"确认密码不能为空！"];
        return NO;
    }
    
    if (![_passTF.text isEqualToString:_comfirmPassTF.text]) {
        [AppDelegate showMessage:@"两次密码不一致！"];
        return NO;
    }
    
    return YES;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation UpdatePassDataSource

- (id)initWithVC:(id)Controller
{
    self = [super init];
    if (self) {
        self.Controller = Controller;
    }
    return self;
}

- (void)updateWithURL:(NSString *)url
{
    [SVProgressHUD show];
    [self get:url];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    int state = [[data objectForKey:@"state"] integerValue];
    if (state == 1) {
        [SVProgressHUD dismissWithSuccess:@"密码修改成功"];
        [AppSetting loginOut];
        
        [_Controller performSelector:@selector(pushOrPopViewController:) withObject:[LoginViewController class] afterDelay:1.5];
    }
    
    if (state == 2) {
        [SVProgressHUD dismiss];
        [AppDelegate showMessage:@"原密码不正确，修改不成功"];
    }
}

@end


